<?php

require_once "script/reccopy.php";
require_once "UserConfig.php";
require_once "FileXML.php";
require_once "pear/XML/Unserializer.php";
require_once "pear/XML/Serializer.php";

class FileList {
		
	var $configfile = "./user/files.xml";
	
 	function getFileList ( $dir_name ){
 		
 		$userconfig = new UserConfig();
 		$user = $userconfig->_getUser();
 		
 		$rootdir = realpath($user['rootdir']);
 		$actdir = realpath($dir_name);
 		//file_put_contents("f", $rootdir." \r\n".$actdir);
 		if (!is_dir($dir_name))
 			return array("valid"=>0,"error"=>"Directory not found!","code"=>"dirnotfound");
 		if ($rootdir != substr($actdir, 0, strlen( $rootdir )))
 			return array("valid"=>0,"error"=>"You don't have permission to browse this directory!", "code"=>"browseperm");
 		if (substr(substr($actdir, strlen( $rootdir )),0,2)==".."){
	 		//file_put_contents("f", substr(substr($actdir, strlen( $rootdir )),0,2));
 			return array("valid"=>0,"error"=>"You don't have permission to browse this directory!", "code"=>"browseperm");
 		}
		$dir = dir( $dir_name );
		$file_list = array();
		while(false !== ($file = $dir->read()))
		{
			$filename = $dir_name.'/'.$file;

			if ( $file == '.'  ) { continue; }

			else if ($file == '..')
			{
				$type = 1;
				array_push( $file_list,  array( 'type'=>$type, 'name' => $file, 'ext' =>'' , 'basename'=>$file, 'size' => '', 'date'=>'', 'perm'=>'' ));
			}
			else if ( is_dir($filename) )
			{
				$type = 2;
				$date = filemtime($filename);
				$perm = base_convert(fileperms($filename),10,8);
 				$perm = substr( $perm, strlen( $perm )-3, strlen($perm));
				array_push( $file_list,  array('type'=>$type, 'name' => $file, 'ext' =>'', 'basename'=>$file,'size' => '', 'date'=>$date, 'perm'=>$perm ));
			}
			else if ( is_file($filename) )
			{
				$type = 3;
				$date = filemtime($filename);
				$perm = base_convert(fileperms($filename),10,8);
 				$perm = substr( $perm, strlen( $perm )-3, strlen($perm));
				$size = sprintf("%u", filesize($filename));
				$name = $file;
				$urlname = urlencode(mb_convert_encoding($file, 'UTF-8'));
				$nameArr = $this->_splitFilename($file);
				$basename = $nameArr[0];
				$ext = $nameArr[1];
				array_push( $file_list,  array('type'=>$type, 'name' => $name, 'ext' => $ext, 'basename'=>$basename, 'urlname'=>$urlname, 'size' => $size, 'date'=>$date, 'perm'=>$perm ));
			}
		}
		$dir->close();
		//
		$path = $dir_name;
		$result = array( "valid"=>1, "path"=>$path, "list"=>$file_list);
		return $result;
   }

   function deleteFiles ( $file_list, $source_dir ){
 		$userconfig = new UserConfig();
 		$user = $userconfig->_getUser();
		if (!$userconfig->_hasPermission($user,'delete'))
			return array("valid"=>0, "error"=>"You don't have permission to delete files!", "code"=>"deleteperm");
		//
		foreach( $file_list as $file ){
			$source_file = $source_dir.'/'.$file['name'];
			if (is_file( $source_file ))
			{
				unlink( $source_file) ;
			}
			else if (is_dir( $source_file )){
				recdelete( $source_file );
			};
		}
	 	$result = $this->getFileList( $source_dir );
	 	$resultObj = array( "valid" =>1, "path"=>$result["path"], "list"=>$result["list"] );
	 	return $resultObj;
 	}
	
 	function overwriteCheck ( $file_list, $source_dir, $target_dir){
 		$userconfig = new UserConfig();
 		$user = $userconfig->_getUser();
		//	
		$ovcount = 0;
		foreach( $file_list as $item )
	 	{
	 		$source_file = $source_dir.'/'.$item['name'];
	 		$target_file = $target_dir.'/'.$item['newname'];
	 		//
	 		/*
			if ($source_file == substr($target_file, 0, strlen($source_file))){
				$resultObj = array( 
								"valid" => 0,
								"error" => "You can't copy a directory to itself!'",
								"code" => "copytoitself"
								);
				return $resultObj;
			};	
			*/
			//
			$ovcount += checkoverwrite($source_file, $target_file);
	 	}
		if ($ovcount>0){
			return array(
				"valid"=>0, 
				"error"=>"You are going to overwrite " . $ovcount . " files. Do you want to proceed?",
				"code" => "overwrite",
				"count" => $ovcount);
		}
		else {
			return array("valid"=>1, "list"=>$file_list, "sourcedir"=>$source_dir, "targetdir"=>$target_dir);
		}
 	}
	
 	function copyFiles ( $file_list, $source_dir, $target_dir, $move = false ){
 		$userconfig = new UserConfig();
 		$user = $userconfig->_getUser();
 		
 		
		if (!$userconfig->_hasPermission($user,'copy')) 
			return array(
				"valid"=>0, 
				"error"=>"You don't have permission to copy files!",
				"code"=>"copyperm");

		if (!$userconfig->_hasPermission($user,'delete')  && $move==true ) 
			return array(
				"valid"=>0, 
				"error"=>"You don't have permission to move files!",
				"code"=>"moveperm");

 		
		// check overwrite once more
		$ow	= $this->overwriteCheck ( $file_list, $source_dir, $target_dir);
		if (!$ow['valid'] && !$userconfig->_hasPermission($user,'overwrite')) 
			return array(
				"valid"=>0, 
				"error"=>"You don't have permission to overwrite files!",
				"code"=>"overwriteperm");
		
		foreach( $file_list as $item )
	 	{
			if (!$userconfig->_hasPermission($user,'extension') && !$this->_checkExtension($item['name'], $item['newname']))
				return array(
					"valid"=>0, 
					"error"=>"You don\'t have permission to change file extensions!",
					"code"=>"extensionperm");
	 		
	 		$source_file = $source_dir.'/'.$item['name'];
	 		$target_file = $target_dir.'/'.$item['newname'];
	 		//
			if ($source_file == substr($target_file, 0, strlen($source_file))){
				$resultObj = array( 
								"valid" => 0,
								"error" => "You can't copy a directory to itself!'",
								"code"=>"copytoitself");
				return $resultObj;
			};	
			//
	 		if ($move) { reccopy( $source_file, $target_file, true ); }
	 		else { reccopy( $source_file, $target_file, false ); }
	 	}

	 	
	 	$sourcelist = $this->getFileList( $source_dir );
	 	$targetlist = $this->getFileList( $target_dir );
	 	$resultObj = array( "valid" => 1 , "sourcelist" => $sourcelist, "targetlist" => $targetlist);
	 	return $resultObj;
 	}
 	
	function makeDir ( $dir_name ){
 		$userconfig = new UserConfig();
 		$user = $userconfig->_getUser();
		if (!$userconfig->_hasPermission($user,'mkdir')) 
			return array(
				"valid"=>0, 
				"error"=>"You don't have permission to make folders!",
				"code"=>"mkdirperm");
		//
		if ( is_dir($dir_name)){
			$resultObj = array( 
							"user" => $user,
							"valid" => 0,
							"error" => "Directory already exists!",
							"code"=>"direxists");
			return $resultObj;
		}
		//
		mkdir( $dir_name ); 		
		chmod( $dir_name, 0777 );
		$dirParts = explode('/', $dir_name);
		array_pop($dirParts);
		$parentdir = implode('/', $dirParts);
		$filelist = $this->getFileList( $parentdir );
 		$resultObj = array( "valid" => 1, "list" => $filelist["list"], "path"=>$filelist["path"]);
 		return $resultObj;		
 	}

 	function rename( $source_dir, $old_name, $new_name ){
 		$userconfig = new UserConfig();
 		$user = $userconfig->_getUser();
		if (!$userconfig->_hasPermission($user,'rename')) 
			return array(
				"valid"=>0, 
				"error"=>"You don't have permission to rename files!",
				"code"=>"renameperm");
		//
		if (!$userconfig->_hasPermission($user,'extension') && !$this->_checkExtension($old_name, $new_name))
			return array(
				"valid"=>0, 
				"error"=>"You don't have permission to change file extensions!",
				"code"=>"extensionperm");

		$oldname = $source_dir.'/'.$old_name;
		$newname = $source_dir.'/'.$new_name;
		
 		if (is_file( $newname ) || is_dir( $newname )){
			$resultObj = array( 
							"user" => $user,
							"valid" => 0,
							"error" => "Target file already exists!",
							"code"=>"targetexists"
							);
			return $resultObj;
 		}
 		//
 		if (is_file( $oldname ) || is_dir( $oldname ))
 		{
 			if (rename( $oldname, $newname )){
			 	$result = $this->getFileList( $source_dir );
			 	return array( "valid" =>1, "path"=>$result["path"], "list"=>$result["list"] );
 			}
 			else {
 				return array(
					"valid"=>0, "error"=>"There was an error renaming the file!", "code"=>"renameerror");
 			}
 		}
 	}
 	
 	function _checkExtension($oldname, $newname){
		$a1 = explode('.', $oldname);
		$a2 = explode('.', $newname);
		if (count($a1)<2 && count($a2)<2)return true;
		
		$ext1 = array_pop($a1);
		$ext2 = array_pop($a2);
		if ($ext1!=$ext2) { return false;}
			else {return true;};
		return false;
 	}	

	function _splitFilename($filename)
	{
	    $pos = strrpos($filename, '.');
	    if ($pos === false){ 
	        return array($filename, ''); // no extension
	    }
	    else if ($pos === 0){
	        return array($filename, ''); // .htaccess
	    }
	    else {
	        $basename = substr($filename, 0, $pos);
	        $extension = substr($filename, $pos+1);
	        return array($basename, $extension);
	    }
	}  	
	
	function readFileList(){
		$unserializer_options = array('forceEnum' => array('folder'), 'parseAttributes'=>true );
		$unserializer = &new XML_Unserializer($unserializer_options);
		$result = $unserializer->unserialize( dirname(__FILE__) ."/" . $this->configfile, true);
		$files = $unserializer->getUnserializedData();
		return $files;		
	}

}

?>
